package cn.jbit.smbms.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.jbit.smbms.Util.AjaxResult;
import cn.jbit.smbms.Util.CommentData;
import cn.jbit.smbms.Util.Pager;
import cn.jbit.smbms.pojo.Bill;
import cn.jbit.smbms.pojo.Provider;
import cn.jbit.smbms.pojo.User;
import cn.jbit.smbms.service.BillService;
import cn.jbit.smbms.service.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/bill")
public class BillController {
    @Autowired
    private BillService billService;
    @Autowired
    private ProviderService providerService;
    @RequestMapping("/list")
    public String list(Map<String,Object>map){
        List<Provider> providers = providerService.providerlist();
        map.put("providers",providers);
        return "bill/list";
    }
    @RequestMapping("/add")
    public String add(Map<String,Object>map){
        List<Provider> providerlist = providerService.providerlist();
        map.put("providerlist",providerlist);
        return "bill/add";
    }
    @RequestMapping("/view")
    public String view(Integer id,Map<String,Object>map){
        try {
            Bill bill = billService.queryBillById(id);
            if (bill != null) {
                map.put("bill",bill);
            }else{
                throw new RuntimeException("查询该条订单出错！");
            }
        } catch (RuntimeException e) {
            map.put("message",e.getMessage());
            e.printStackTrace();
        }
        return "bill/view";
    }
    @RequestMapping("/modify")
    public String modify(Integer id,Map<String,Object>map){
        Bill resultBill=billService.queryBillById(id);
        List<Provider> providerlist = providerService.providerlist();
        map.put("bill",resultBill);
        map.put("providerlist",providerlist);
        return "bill/modify";
    }
    @ResponseBody
    @RequestMapping("/doModify")
    public Object doModify(Bill bill,HttpSession session){
        AjaxResult result=new AjaxResult();
        try {
            User loginUser=(User)session.getAttribute(CommentData.LOGIN_SESSION);
            if (null!=bill){
                bill.setModifyBy(loginUser.getId());
                bill.setModifyDate(new Date());
                int count=billService.updateByBill(bill);
                result.setSuccess(count==1);
            }else{
                throw new RuntimeException("订单对象为空！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("修改订单出错！");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(Integer id){
        AjaxResult result=new AjaxResult();
        try {
            int count=billService.deleteById(id);
            result.setSuccess(count==1);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("删除订单出错！");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/doAdd")
    public Object doAdd(Bill bill, HttpSession session){
        AjaxResult result=new AjaxResult();
        try {
            User loginUser=(User)session.getAttribute(CommentData.LOGIN_SESSION);
            bill.setCreatedBy(loginUser.getId());
            bill.setCreationDate(new Date());
            int count=billService.doAdd(bill);
            result.setSuccess(count==1);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("新增订单出错！");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/querylist")
    public Object querylist(Integer pageSize, Integer pageIndex,String queryProductName,Integer queryProviderId,Integer queryIsPayment){
        AjaxResult result=new AjaxResult();
        try {
            Map<String,Object>param=new HashMap<>();
            param.put("pageSize",pageSize);
            param.put("pageIndex",pageIndex);
            param.put("pageForm",(pageIndex-1)*pageSize);
            param.put("productName",queryProductName);
            param.put("providerId",queryProviderId);
            param.put("isPayment",queryIsPayment);
            Pager pager=new Pager<>();
            pager.setPageSize(pageSize);
            pager.setPageIndex(pageIndex);
            pager.setTotalCount(billService.queryPageCount(param));
            pager.setList(billService.queryPageList(param));
            List<Provider>providers=providerService.providerlist();
            param.put("providers",providers);
            result.setPage(pager);
            result.setParam(param);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("查询订单出错！");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/downExcelModel")
    public Object downExcelModel(ModelMap map, HttpServletRequest request, HttpServletResponse response){
        AjaxResult result=new AjaxResult();
        List<Bill>list=new ArrayList<>();
        try {
            ExportParams params=new ExportParams("订单信息表","sheet1", ExcelType.XSSF);
            map.put(NormalExcelConstants.DATA_LIST,list);
            map.put(NormalExcelConstants.CLASS,Bill.class);
            map.put(NormalExcelConstants.PARAMS,params);
            map.put(NormalExcelConstants.FILE_NAME,"订单信息表模板");
            PoiBaseView.render(map,request,response,NormalExcelConstants.EASYPOI_EXCEL_VIEW);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/downExcelAll")
    public Object downExcelAll(ModelMap map,HttpServletRequest request,HttpServletResponse response){
        AjaxResult result=new AjaxResult();
        List<Bill>bills=null;
        try {
            bills=billService.queryAll();
            if (bills!=null) {
                ExportParams params=new ExportParams("订单信息表","订单",ExcelType.XSSF);
                map.put(NormalExcelConstants.DATA_LIST,bills);
                map.put(NormalExcelConstants.CLASS,Bill.class);
                map.put(NormalExcelConstants.PARAMS,params);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                map.put(NormalExcelConstants.FILE_NAME,"订单信息表"+sdf.format(new Date()));
                PoiBaseView.render(map,request,response,NormalExcelConstants.EASYPOI_EXCEL_VIEW);
                result.setSuccess(true);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            e.printStackTrace();
        }


        return result;
    }

    @RequestMapping("/uploadExcelByProvider")
    public Object uploadExcelByProvider(Integer excelProviderId, MultipartFile excelBillFile, HttpSession session, Model model){
        AjaxResult result=new AjaxResult();
        try {
            if (excelBillFile.getSize()>0){
                ImportParams params=new ImportParams();
                params.setHeadRows(1);
                params.setTitleRows(1);
                List<Bill> bills = ExcelImportUtil.importExcel(excelBillFile.getInputStream(), Bill.class, params);
                if (bills != null) {
                    List<Bill>list=new ArrayList<>();
                    User user=(User) session.getAttribute(CommentData.LOGIN_SESSION);
                    for (Bill bill :
                            bills) {
                        bill.setProviderId(excelProviderId);
                        bill.setCreatedBy(user.getId());
                        bill.setCreationDate(new Date());
                        list.add(bill);
                    }
                    int count=billService.insertBillByBatch(list);
                    if (count>0) {
                        result.setSuccess(true);

                    }
                }
            }else{
                throw new RuntimeException("未选择上传文件！");
            }


        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        model.addAttribute("result",result);
        return"redirect:/bill/list";
    }

}
